package collect

import (
	"errors"
	"net/smtp"
	"strings"

	pslog "gitee.com/xuesongtao/ps-log"
	"github.com/gogf/gf/os/glog"
	jemail "github.com/jordan-wright/email"
)

type ToEmail struct {
	cli          *jemail.Email
	SmtpServer   string   `json:"smtp_server"` // smtp 服务器(host:prot)
	SendUserName string   `json:"send_user_name"`
	SendPassword string   `json:"send_password"` // 授权码
	From         string   `json:"from"`          // 发件人
	To           []string `json:"to"`            // 收件人
	Cc           []string `json:"cc"`            // 抄送人
}

func (t *ToEmail) Init() {
	t.cli = jemail.NewEmail()
	if t.SmtpServer == "" {
		t.SmtpServer = defaultSmtpServer
	}

	if t.SendUserName == "" {
		t.SendUserName = defaultSendUserName
	}

	if t.SendPassword == "" {
		t.SendPassword = defaultSendPassword
	}

	if t.From == "" {
		t.From = defaultFrom
	}
}

func (t *ToEmail) WriteTo(bus *pslog.LogHandlerBus) {
	glog.Info("push email")
	t.Push(&PushParam{
		Title:   ParsePushLogTitle(bus),
		Content: bus.Msg,
	})
}

func (t *ToEmail) SetFrom(from string) *ToEmail {
	t.From = from
	return t
}

func (t *ToEmail) SetTo(to string) *ToEmail {
	if t.To == nil {
		t.To = make([]string, 0, 5)
	}
	t.To = append(t.To, to)
	return t
}

func (t *ToEmail) SetCc(Cc string) *ToEmail {
	if t.Cc == nil {
		t.Cc = make([]string, 0, 5)
	}
	t.Cc = append(t.Cc, Cc)
	return t
}

func (t *ToEmail) Push(param *PushParam) error {
	// defer t.reset()
	email := t.cli
	email.From = t.From
	email.To = t.To
	email.Cc = t.Cc
	if param.Title == "" {
		param.Title = ErrLogTitle
	}
	email.Subject = param.Title
	email.Text = []byte(param.Content)
	serverHostLastIndex := strings.Index(t.SmtpServer, ":")
	if serverHostLastIndex < 0 {
		return errors.New("SmtpServer not have port")
	}
	serverHost := t.SmtpServer[0:serverHostLastIndex]
	if err := email.Send(t.SmtpServer, smtp.PlainAuth("", t.SendUserName, t.SendPassword, serverHost)); err != nil {
		return err
	}
	return nil
}
